﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Tasks
{
    public class Utilities
    {

        public static List<FileInfo> GetFiles(string baseFolder, string[] excluded, string[] include)
        {
            var items = new List<FileInfo>();
            var baseDir = new DirectoryInfo(baseFolder);

            foreach (var file in baseDir.GetFiles())
            {
                if (MatchesFilter(file.Name, excluded)) continue;
                if (include != null && !MatchesFilter(file.Name, include)) continue;

                items.Add(file);
            }

            foreach (var dir in baseDir.GetDirectories())
            {
                if (MatchesFilter(dir.Name, excluded)) continue;
                if (include != null && !MatchesFilter(dir.Name, include)) continue;
                items.AddRange(GetFiles(dir.FullName, excluded, include));
            }

            return items;
        }

        public static bool MatchesFilter(string name, string[] filters)
        {
            if (filters == null || filters.Length == 0) return false;

            name = name.ToLowerInvariant();

            foreach (var e in filters)
            {
                var filter = e.ToLowerInvariant();
                if (filter.StartsWith("*") && filter.EndsWith("*"))
                {
                    if (name.Contains(filter.Substring(1, filter.Length - 2))) return true;
                }
                else if (filter.StartsWith("*"))
                {
                    if (name.EndsWith(filter.Substring(1))) return true;
                }
                else if (filter.EndsWith("*"))
                {
                    if (name.StartsWith(filter.Substring(0, filter.Length - 1))) return true;
                }
                else
                {
                    if (name == filter) return true;
                }
            }
            return false;
        }

        public static void CopyDirectory(string src, string dest)
        {
            CopyDirectory(src, dest, null, null);
        }

        public static void CopyDirectory(string src, string dest, string[] exclude, string[] include)
        {
            foreach (var f in Utilities.GetFiles(src, exclude, include))
            {
                var destPath = f.FullName.Replace(src, dest);
                var destFolder = Path.GetDirectoryName(destPath);
                if (!Directory.Exists(destFolder))
                    Directory.CreateDirectory(destFolder);
                f.CopyTo(destPath, true);
            }
        }

        
    }

    

}
